use crate::plan_struct::{ID, Plan, PlanSet, Tag};
use std::ops::{Deref, DerefMut};
use std::sync::{Arc, Mutex, RwLock};
#[derive(Debug, PartialEq)]
pub enum Operation {
    TryShow(ID),
    TryMoveTo(ID),
    CreateNew,
    TryDeleteSelf,
    TryShowParent,
    TryShowChild(ID),
    Search(Vec<Tag>),
    ShowSearchResult,
    Quit,
}
pub enum Next {
    ShowSearchResult,
    Quit,
}
pub enum SearchResult {
    None,
    TryShow(ID),
    Continue,
}
pub trait UI {
    fn display(&mut self, plan: &mut Plan) -> Vec<Operation>;
    fn display_msg(&mut self, msg: &str);
    fn display_search_result(&mut self, results: &[Arc<RwLock<Plan>>]) -> SearchResult;
}
pub struct OperationHandler<'a> {
    current_plan: Arc<RwLock<Plan>>,
    plan_set: &'a mut PlanSet,
}
impl<'a> OperationHandler<'a> {
    pub fn new(plan_set: &'a mut PlanSet) -> Self {
        let current_plan = plan_set.root.deref().clone();
        OperationHandler {
            current_plan,
            plan_set,
        }
    }
}
impl<'a> OperationHandler<'a> {
    pub fn display<U: UI>(&mut self, ui: &mut U) -> Option<Next> {
        let mut ops = ui.display(self.current_plan.write().unwrap().deref_mut());
        operations_filter(&mut ops);
        for op in ops {
            match op {
                Operation::Quit => return Some(Next::Quit),
                Operation::TryMoveTo(id) => {
                    if let Some(new_parent) = self.plan_set.set.get(&id) {
                        if !Plan::move_to(&self.current_plan, new_parent) {
                            ui.display_msg("不可以创建循环引用");
                        }
                    } else {
                        ui.display_msg("没有这个ID");
                    }
                }
                Operation::CreateNew => {
                    let new_current_plan = self.plan_set.create_new_plan(&self.current_plan);
                    self.current_plan = new_current_plan;
                }
                Operation::TryDeleteSelf => {
                    let current_plan = self.current_plan.clone();
                    let mut current_plan = current_plan.write().unwrap();
                    if let Some(parent) = &current_plan.parent {
                        let parent = parent.upgrade().unwrap();
                        parent.write().unwrap().childs.remove(&current_plan.gid);
                        self.plan_set.remove(&current_plan.gid);
                        let mut vec = Vec::new();
                        while let Some((_, plan)) = current_plan.childs.pop_last() {
                            vec.push(plan);
                        }
                        while let Some(plan) = vec.pop() {
                            let mut plan = plan.write().unwrap();
                            self.plan_set.remove(&plan.gid);
                            while let Some((_, plan)) = plan.childs.pop_last() {
                                vec.push(plan);
                            }
                        }
                        self.current_plan = parent;
                    } else {
                        ui.display_msg("不可以删除根计划");
                    }
                }
                Operation::TryShowParent => {
                    let current_plan = self.current_plan.clone();
                    if let Some(parent) = &current_plan.read().unwrap().parent {
                        self.current_plan = parent.upgrade().unwrap();
                    } else {
                        ui.display_msg("没有父计划");
                    }
                }
                Operation::TryShowChild(index) => {
                    let current_plan = self.current_plan.clone();
                    if let Some(child) = current_plan.read().unwrap().childs.get(&index) {
                        self.current_plan = child.clone();
                    } else {
                        ui.display_msg("没有这个子计划");
                    }
                }
                Operation::TryShow(id) => {
                    if let Some(plan) = self.plan_set.set.get(&id) {
                        self.current_plan = plan.clone();
                    } else {
                        ui.display_msg("没有这个ID");
                    }
                }
                Operation::Search(tags) => {
                    *SEARCH_RESULT.lock().unwrap() = self.plan_set.search(&tags);
                    return Some(Next::ShowSearchResult);
                }
                Operation::ShowSearchResult => {
                    let mut search_result_lock = SEARCH_RESULT.lock().unwrap();
                    let res = ui.display_search_result(&search_result_lock);
                    match res {
                        SearchResult::TryShow(id) => {
                            if let Some(plan) = self.plan_set.set.get(&id) {
                                self.current_plan = plan.clone();
                            } else {
                                ui.display_msg("没有这个ID");
                            }
                            search_result_lock.clear();
                        }
                        SearchResult::None => search_result_lock.clear(),
                        SearchResult::Continue => return Some(Next::ShowSearchResult),
                    }
                }
            };
        }
        None
    }
}
pub(crate) static SEARCH_RESULT: Mutex<Vec<Arc<RwLock<Plan>>>> = Mutex::new(Vec::new());

fn operations_filter(ops: &mut Vec<Operation>) {
    if ops.contains(&Operation::Quit) {
        ops.clear();
        ops.push(Operation::Quit);
    }
}
